package com.sensePlusVR.setting.bluetooth;


import org.xutils.x;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.cavan.android.CavanBleDevice;
import com.cavan.android.CavanBleDeviceAdapter;
import com.cavan.android.CavanBleScanner;
import com.jwaoo.android.JwaooBleToy;
import com.sensePlusVR.application.VRApplication;
import com.sensePlusVR.base.BaseActivity;
import com.sensePlusVR.main.R;
import com.sensePlusVR.setting.bluetooth.BluetoothPlayer.BTEvent;
import com.sensePlusVR.utils.AppManager;
import com.sensePlusVR.utils.Constant;
import com.sensePlusVR.utils.GameController;
import com.sensePlusVR.utils.JumpGameTest;
import com.sensePlusVR.utils.MyDialogUtil;
import com.sensePlusVR.utils.MyLog;
import com.sensePlusVR.utils.MyPageJump;
import com.sensePlusVR.utils.MySharedPreferences;
import com.sensePlusVR.utils.MyToast;
import com.sensePlusVR.widget.dialog.BlueOpenBlueDialog;
import com.sensePlusVR.widget.dialog.BlueOpenBlueDialog.BlueEnable;
/**
 * 
 * @author: Loren
 * @create: 2016-8-10下午3:07:07
 * @desc: 蓝牙列表扫描
 *
 */
@SuppressLint({ "NewApi", "InflateParams" })
@ContentView(R.layout.activity_setting_bluscance)
public class BlueScannerActivity extends BaseActivity{

	private static final String TAG = BlueScannerActivity.class.getSimpleName();
	private BluetoothManager mBluetoothManager;
	private BluetoothAdapter mBluetoothAdapter;

	private ListView mListViewDevices;
	private CavanBleDeviceAdapter mBleDeviceAdapter;
	private CavanBleScanner mBleScanner;
	
	private AnimationDrawable animationDrawableTip;
	private AnimationDrawable animationDrawableItem;
	private ImageView blue_rotate_iv;
	private ImageView blue_scan_iv;
	
	
	private String macAddr;
	private String macName;
	private int blueGetViewCount = 0;

	
	private VRApplication vrApplication;
	
	private String lastMacAddr;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyLog.d(TAG, "onCreate ...222");
		initViewAndData();
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		MyLog.d(TAG,"onNewIntent...");
		initViewAndData();
	}

	private void initViewAndData() {
		AppManager.getInstance().addActivity(this);
		
		vrApplication = (VRApplication) getApplication();
		lastMacAddr = MySharedPreferences.getString(this, Constant.SP_BLUE_ADDRESS);
		blueGetViewCount = 0;
		blue_rotate_iv = (ImageView) findViewById(R.id.blue_rotate_iv);
		 //开启动画   
		blue_rotate_iv.setImageResource(R.drawable.blue_loading);
		animationDrawableTip = (AnimationDrawable) blue_rotate_iv.getDrawable();
		startLoadingAnim(animationDrawableTip, blue_rotate_iv);
		mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
		mBluetoothAdapter = mBluetoothManager.getAdapter();
		
		mListViewDevices = (ListView) findViewById(R.id.listViewDevices);
		
		mBleDeviceAdapter = new CavanBleDeviceAdapter(mListViewDevices) {

			@Override
			protected void selectDevice(final View view, CavanBleDevice device) {
				stopScan();
				// 获取连接Mac
				macAddr = device.getDevice().getAddress();
				macName = device.getDevice().getName();
				MyLog.d(TAG, "selectDevice 111 ==" + System.currentTimeMillis());
				vrApplication.toBTDisconnect();
				vrApplication.tryConnectBT(macAddr);
				MyLog.d(TAG, "selectDevice 222 ==" + System.currentTimeMillis());
				
				//当点击第一个连接，然后点击第二个连接，让第一个不显示连接动画
						if(blue_scan_iv != null){
							blue_scan_iv.setVisibility(View.INVISIBLE);
						}
						
						blue_scan_iv = (ImageView) view
								.findViewById(R.id.blue_scan_iv);
						blue_scan_iv.setImageResource(R.drawable.blue_loading);
						 animationDrawableItem = (AnimationDrawable) blue_scan_iv
								.getDrawable();
				
				 stopLoadingAnim(animationDrawableTip, blue_rotate_iv);
				 startLoadingAnim(animationDrawableItem, blue_scan_iv);
			}
			
			   @Override
			public View getView(CavanBleDevice device, View convertView,
					ViewGroup parent) {
				   MyLog.d(TAG, "getView...start");
				ViewHolder holder = null;
				if (convertView == null) {
					convertView = LayoutInflater.from(BlueScannerActivity.this)
							.inflate(R.layout.activity_blue_item, null);
					holder = new ViewHolder();
					holder.blue_icon_iv = (ImageView) convertView
							.findViewById(R.id.blue_icon_iv);
					holder.blue_name_tv = (TextView) convertView
							.findViewById(R.id.blue_name_tv);
					holder.blue_scan_iv = (ImageView) convertView
							.findViewById(R.id.blue_scan_iv);
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
				
				if (device != null) {
					MyLog.d(TAG, "getView...device : " + device.toString());
				// 设置数据
				String blueName = device.getName();
				String blueAddress = device.getDevice().getAddress();
				String[] blueAddressSub = blueAddress.split(":");
				String blueAddressNew = null;
				if (blueAddressSub != null && blueAddress.length() >= 2) {
					blueAddressNew = blueAddressSub[blueAddressSub.length - 2]
							+ blueAddressSub[blueAddressSub.length - 1];
				}
				String displayName = blueName + blueAddressNew;
				if (blueName != null) {
					if (blueName.contains(Constant.SENSE_TUBE)) {
						holder.blue_icon_iv
								.setImageResource(R.drawable.plane_cup);
					} else if (blueName.contains(Constant.SENSE_BAND)) {
						holder.blue_icon_iv
								.setImageResource(R.drawable.bracelet_icon);
					}
					holder.blue_name_tv.setText(displayName);
				}
					// 自动连接
					if (device.getDevice().getAddress().equals(lastMacAddr)) {
						blueGetViewCount++;
						if (blueGetViewCount == 1) {
							stopScan();
							MyLog.d(TAG, "getView 111 ==" + System.currentTimeMillis());
							vrApplication.toBTDisconnect();
							vrApplication.tryConnectBT(lastMacAddr);
							MyLog.d(TAG, "getView 222 ==" + System.currentTimeMillis());

							if (blue_scan_iv != null) {
								blue_scan_iv.setVisibility(View.INVISIBLE);
							}

							blue_scan_iv = holder.blue_scan_iv;

							blue_scan_iv.setImageResource(R.drawable.blue_loading);
							animationDrawableItem = (AnimationDrawable) blue_scan_iv
									.getDrawable();
							MyLog.d(TAG, "getView...start animation");
							stopLoadingAnim(animationDrawableTip,
									blue_rotate_iv);
							MyLog.d(TAG, "animationDrawableItem isrunning 1 : " + animationDrawableItem.isRunning());
							startLoadingAnim(animationDrawableItem,
									blue_scan_iv);
							MyLog.d(TAG, "animationDrawableItem isrunning 2: " + animationDrawableItem.isRunning());
						}
					}
				}
				return convertView;
			}

			class ViewHolder {
				public ImageView blue_icon_iv;
				public TextView blue_name_tv;
				public ImageView blue_scan_iv;
			}
		};
	}
	

	
	/**
	 * 开始扫描蓝牙
	 */
	private void startBlueScan() {
		mBleScanner = new CavanBleScanner(this) {
			@Override
			protected void onScanResult(CavanBleDevice[] devices, CavanBleDevice device) {
				mBleDeviceAdapter.setDevices(devices, device);
			}
		};
		
		if(mBleScanner!=null)
		mBleScanner.startScan(null, JwaooBleToy.BT_NAMES);
	}
	
	/**
	 * 停止扫描蓝牙
	 */
	private void stopScan() {
		if(mBleScanner!=null)
		mBleScanner.stopScan();
	}
	
	
	private void startLoadingAnim(AnimationDrawable animationDrawable,
			 ImageView imageView) {
				if(imageView == null)return;
				if (imageView.getVisibility() == View.INVISIBLE)
					imageView.setVisibility(View.VISIBLE);
					animationDrawable.start();
	}
	
	private void stopLoadingAnim(AnimationDrawable animationDrawable,
			ImageView imageView) {
				if(imageView == null)return;
				if (imageView.getVisibility() == View.VISIBLE)
					imageView.setVisibility(View.INVISIBLE);
					animationDrawable.stop();
	}
	
	private BlueEnable blueEnable = new BlueEnable(){

		@Override
		public void onBlueEnable() {
			startBlueScan();
		}

		@Override
		public void onBandDismiss() {
			finish();
		}
		
	};
	
	
	private OnDismissListener dismissListener = new OnDismissListener(){
	
		@Override
		public void onDismiss(DialogInterface dialog) {
			MyLog.d(TAG, "dialog dismiss...");
			startLoadingAnim(animationDrawableTip, blue_rotate_iv);
		}
	};
	
	@Event(value = { R.id.title_bar_left_ib })
	private void setViewOnClick(View view) {
		switch (view.getId()) {
		case R.id.title_bar_left_ib:
			AppManager.getInstance().finishActivity(this);
			break;

		default:
			break;
		}
	}
	

	@Override
	public void finish() {
		super.finish();
		stopScan();
		MyLog.d(TAG, "finish is connect : " + vrApplication.isBTConnected());
		if(!vrApplication.isBTConnected())
		vrApplication.toBTDisconnect();
	}

	
	public boolean isMainThread() {
	    return Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId();
	}

	
	private BTEvent mBTEvent = new BTEvent() {
		
		@Override
		public void onConnected(boolean isConnected) {
				MyLog.d(TAG, "Bluetooth is connected : " + isConnected + " isMainThread : " + isMainThread());
				if(isConnected){
					//连接成功保存当前Mac,若需修改Mac,则需要进入设置执行.
					MySharedPreferences.save(BlueScannerActivity.this, Constant.SP_BLUE_ADDRESS, macAddr);
					MySharedPreferences.save(BlueScannerActivity.this, Constant.SP_BLUE_NAME, macName);
					boolean isFromSetting = MySharedPreferences.getBoolean(BlueScannerActivity.this, Constant.SP_BLUE_IS_FROM_SETTING);
					MyLog.d(TAG, "isFromSetting : " + isFromSetting);
					if(!isFromSetting){
						
						if(Constant.nativeBundleSwitch){
							
							
							if(GameController.getRealGame()){
								
								JumpGameTest.jumpRealActivity(BlueScannerActivity.this, GameController.getGameMode()==Constant.GAME_MODE_VR,GameController.getGameItem());
							}else{
								
								JumpGameTest.jumpVRActivity(BlueScannerActivity.this,GameController.getGameMode()==Constant.GAME_MODE_VR);
							}
							
							
						}else{
							
							GameController.GameStart(BlueScannerActivity.this);	
						}
						
					}else{
						MyToast.showMessage(BlueScannerActivity.this, R.string.blue_connected_success);
					}
					
					MyLog.d(TAG, "Bluetooth is connected 111");
//					runOnUiThread(new Runnable() {
//						public void run() {
//							
//							stopLoadingAnim(animationDrawableItem, blue_scan_iv);
//							
//						}
//					});
							
					AppManager.getInstance().finishActivity(BlueScannerActivity.this);
				}else{
					
					vrApplication.toBTDisconnect();
					MyPageJump.pageJump(BlueScannerActivity.this, BlueDisconnectActivity.class);
				}
		}
	};
	
	
	@Override
	public void setMyContentView() {
		x.view().inject(this);
	}
	
	/**
	 * assets文件加下指定文件copy到sdcard中
	 */
/*	private void copyFileToSDCard(){
		if(!FileUtils.isFileExist(Constant.FILE_UPDATE)){
			String fileName = "jwaoo-toy.hex";
			FileUtils.copyAssetToSDCard(this.getAssets(), fileName, Constant.FILE_UPDATE);
		}
	}*/
	
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
		
		MyLog.d(TAG, "onActivityResult...");
	}
	
	/**
	 * 获取已经保存的device
	 */
/*    private BluetoothDevice getSaveDevice(){
    	String addressSP = MySharedPreferences.getString(BlueScannerActivity.this, Constant.SP_BLUE_ADDRESS);
    	if(addressSP != ""){
    		BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(addressSP);
    		return device;
    	}
		return null;
    }*/
	

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		vrApplication.registerBT();
		
		initialBlueScan();
		
		vrApplication.setBTEvent(mBTEvent);
		
		
	}

	private void initialBlueScan() {
		
		if (!mBluetoothAdapter.isEnabled()) {
			BlueOpenBlueDialog dialog = new BlueOpenBlueDialog(
					BlueScannerActivity.this, R.style.FullScreen_Dialog_Half_Tran);
			dialog.show();
			MyDialogUtil.setDialogFullScreen(BlueScannerActivity.this, dialog);
			dialog.setOnDismissListener(dismissListener);
			dialog.setOnBlueEnable(blueEnable);
			stopLoadingAnim(animationDrawableTip, blue_rotate_iv);
			return;
		}
		
		startBlueScan();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		vrApplication.unregisgerBT();
		
		vrApplication.setBTEvent(null);
	}
	
}
